package com.pur.zsms.pmsnmanage.role.web;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import net.sf.cglib.beans.BeanCopier;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.pur.zsms.common.exception.GenericException;
import com.pur.zsms.common.support.PageController;
import com.pur.zsms.common.support.PaginationSupport;
import com.pur.zsms.foodmanage.food.po.FoodPo;
import com.pur.zsms.foodmanage.food.vo.FoodVo;
import com.pur.zsms.pmsnmanage.menu.po.MenuPo;
import com.pur.zsms.pmsnmanage.menu.service.IMenuService;
import com.pur.zsms.pmsnmanage.menu.service.impl.MenuServiceImpl;
import com.pur.zsms.pmsnmanage.menu.vo.MenuVo;
import com.pur.zsms.pmsnmanage.role.po.RoleMenuPo;
import com.pur.zsms.pmsnmanage.role.po.RolePo;
import com.pur.zsms.pmsnmanage.role.service.IRoleService;
import com.pur.zsms.pmsnmanage.role.vo.RoleVo;
import com.pur.zsms.pmsnmanage.user.po.UserPo;
import com.pur.zsms.pmsnmanage.user.po.UserRolePo;
import com.pur.zsms.pmsnmanage.user.service.IUserService;
import com.pur.zsms.pmsnmanage.user.vo.UserVo;
import com.pur.zsms.systemsetting.datadictionary.po.CodeType;
import com.pur.zsms.systemsetting.datadictionary.vo.CodeVo;

@Controller
@RequestMapping(value = "/role")
public class RoleControllor {

	@SuppressWarnings("unused")
	private static final Logger log = LoggerFactory.getLogger(RoleControllor.class);

	protected int page = 1;

	protected int pageSize = 15;

	PaginationSupport pageList;

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	@Resource(name = "roleService")
	private IRoleService roleService;

	@Resource(name = "menuService")
	private IMenuService menuService;

	@RequestMapping(value = "/findRole.do", method = { RequestMethod.POST })
	@ResponseBody
	public String roleList(@RequestParam(required = false) String page,
	        @RequestParam(required = false) String rows, RoleVo roleVo) throws GenericException {
		JSONObject json = new JSONObject();
		if (page == null || page.equals(""))
			page = "1";
		if (rows == null || rows.equals(""))
			rows = "10";
		PageController pageController = new PageController(Integer.parseInt(page), Integer.parseInt(rows));
		this.pageList = roleService.listRole(pageController, roleVo);
		List items = pageList.getItems();
		List<RoleVo> voList = new ArrayList<RoleVo>();
		List<RoleMenuPo> roleMenuPos = new ArrayList<RoleMenuPo>();
		try {
			if (items != null) {
				for (int i = 0; i < items.size(); i++) {
					RolePo po = (RolePo) items.get(i);
					RoleVo vo = new RoleVo();

					BeanUtils.copyProperties(vo, po);
					roleMenuPos = roleService.findMenusByRole(vo.getRoleId());
					String menunames = "";
					for (int j = 0; j < roleMenuPos.size(); j++) {
						MenuPo menuPo = menuService.findMenu(roleMenuPos.get(j).getMenuId().toString());
						if (j == 0) {
							menunames = menuPo.getMenuName();
						} else {
							menunames = menunames + "<br>" + menuPo.getMenuName();
						}
						System.out.println(menunames);
					}
					vo.setMenuName(menunames);
					voList.add(vo);
				}
			}
		} catch (Exception e) {
			json.put("success", false);
			return json.toString();
		}

		json.put("success", true);
		json.put("total", pageList.getTotalCount());
		json.put("rows", voList);
		return json.toString();
	}

	@RequestMapping(value = "/preUpdateRole.do", method = { RequestMethod.GET })
	public ModelAndView preUpdateRole(@RequestParam Long roleId) {
		JSONObject json = new JSONObject();
		List<MenuPo> menuList = null;
		RolePo rolePo = null;
		RoleVo roleVo = new RoleVo();
		List<RoleMenuPo> roleMenus = null;
		try {
			rolePo = roleService.findRole(roleId);

			BeanCopier copier = BeanCopier.create(RolePo.class, RoleVo.class, false);
			copier.copy(rolePo, roleVo, null);
			roleMenus = roleService.findMenusByRole(roleId);
			String menuIdAll = "";
			for (RoleMenuPo roleMenuPo : roleMenus) {
				if (!menuIdAll.equals("")) {
					menuIdAll += ',';
				}
				menuIdAll += roleMenuPo.getMenuId();
			}
			roleVo.setMenuIdAll(menuIdAll);

		} catch (GenericException e) {
			e.printStackTrace();
		}
		Map map = new HashMap();
		map.put("menuList", menuList);
		// map.put("roleMenus", roleMenus);
		map.put("role", roleVo);
		return new ModelAndView("/pmsnmanage/role/editRole", map);
	}

	@RequestMapping(value = "/findRoleMenus.do", method = { RequestMethod.GET })
	@ResponseBody
	public String findRoleMenus(@RequestParam Long roleId) {
		JSONObject json = new JSONObject();
		List<RoleMenuPo> roleMenus = null;
		try {
			roleMenus = roleService.findMenusByRole(roleId);
			json.put("success", true);
			json.put("menus", roleMenus);
		} catch (Exception e) {
			e.printStackTrace();
			json.put("success", false);
		}
		log.info(json.toString());
		return json.toString();
	}

	@RequestMapping(value = "/saveRole.do", method = { RequestMethod.POST })
	@ResponseBody
	public String saveRoleAndMenu(RoleVo roleVo, HttpSession session) {
		JSONObject json = new JSONObject();
		try {
			UserPo userPo = (UserPo) session.getAttribute("user");
			roleVo.setInsertBy(userPo.getUserName());
			roleService.addRoleMenu(roleVo);
			json.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			json.put("msg", "失败");
			json.put("success", false);
		}
		return json.toString();
	}

	@RequestMapping(value = "/updateRole.do", method = { RequestMethod.POST })
	@ResponseBody
	public String updateRole(RoleVo roleVo, HttpSession session) {
		JSONObject json = new JSONObject();
		try {
			UserPo userPo = (UserPo) session.getAttribute("user");
			roleVo.setInsertBy(userPo.getUserName());
			roleVo.setUpdateBy(userPo.getUserName());
			roleService.updateRoleMenu(roleVo);
			json.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			json.put("success", false);
		}
		return json.toString();
	}

	@RequestMapping(value = "/deleteRole.do", method = { RequestMethod.POST })
	@ResponseBody
	public String deleteRole(Long roleId) {
		JSONObject json = new JSONObject();
		try {
			List<UserRolePo> userRoles = roleService.findUserRoles(roleId);
			if (userRoles == null || userRoles.size() == 0) {
				roleService.deleteRoleMenu(roleId);
				json.put("success", true);
			} else {
				json.put("msg", "该角色已被用户使用！");
			}
		} catch (Exception e) {
			json.put("success", false);
		}
		return json.toString();
	}

	@RequestMapping(value = "/preSaveRole.do", method = { RequestMethod.GET })
	public ModelAndView preSaveRole() {
		JSONObject json = new JSONObject();
		List<MenuPo> menuList = null;

		try {
			menuList = roleService.listAllMenu(); // 查询所有菜单信息
		} catch (GenericException e) {
			e.printStackTrace();
		}
		Map map = new HashMap();
		map.put("menuList", menuList);
		return new ModelAndView("/pmsnmanage/role/addRole", map);
	}

	@RequestMapping(value = "/findMenu.do", method = { RequestMethod.POST })
	@ResponseBody
	public String findMenu(String id) {
		JSONObject json = new JSONObject();
		String a = "";
		try {

			if (id != null && !id.equals("")) {
				a = roleService.getAllMenuJson(Integer.valueOf(id));
			} else {
				a = "[{ \"id\":0, \"text\":\"菜单目录\" ,\"state\":\"closed\",\"folder\":\"1\"}] ";
			}
		} catch (GenericException e) {
			e.printStackTrace();
		}
		return a;
		// return json.toString();
	}

	@RequestMapping(value = "/findMenuForUpdate.do", method = { RequestMethod.POST })
	@ResponseBody
	public String findMenuForUpdate(String id, String menuIdAll) {
		JSONObject json = new JSONObject();
		String a = "";
		try {

			if (id != null && !id.equals("")) {
				a = roleService.getAllMenuJson(Integer.valueOf(id));
			} else {
				a = roleService.getAllMenuJson(menuIdAll);
			}
		} catch (GenericException e) {
			e.printStackTrace();
		}
		return a;
		// return json.toString();
	}
}
